<script setup lang="ts">
import { useChannelStore } from '@/stores/channel'
import type { ArticleItem } from '@/types/data'
import axios from 'axios'
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'

// 从pinia仓库中获取useChannelStore对象
const channelStore = useChannelStore()

// 专栏数据
const channelList = ref<ArticleItem[]>([])

// 侦听channelId的变化，当channelId发生变化时，请求专栏数据
watch(
  () => channelStore.channelId,
  async () => {
    // 请求专栏数据
    const res = await axios.get(`http://geek.itheima.net/v1_0/articles`, {
      params: {
        channel_id: channelStore.channelId,
        timestamp: Date.now(),
      },
    })
    // 存储专栏数据
    channelList.value = res.data.data.results
  },
  {
    deep: true,
    immediate: true,
  },
)

// 获取路由
const router = useRouter()

// 跳转详情页函数
const goToDetail = (art_id: string) => {
  // 跳转路由
  router.push({
    name: 'ArticleDetail',
    params: {
      id: art_id,
    },
  })
}
</script>

<template>
  <div class="article-list">
    <div
      class="article-item"
      v-for="item in channelList"
      :key="item.art_id"
      @click="goToDetail(item.art_id)"
    >
      <p class="title">{{ item.title }}</p>
      <img class="img" v-for="(img, index) in item.cover.images" :key="index" :src="img" alt="" />
      <div class="info">
        <span>{{ item.aut_name }}</span>
        <span>{{ item.comm_count }}评论</span>
        <span>{{ item.pubdate }}</span>
      </div>
    </div>
  </div>
</template>
